from django.conf import settings
from django.shortcuts import render

# Create your views here.
from django.views import View


#test
from itsdangerous import TimedJSONWebSignatureSerializer
from rest_framework import mixins
from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

#
from rest_framework.viewsets import GenericViewSet

from users import serializers
from users.models import User
from users.serializers import CreateUserSerializer, UserDetailSerializer, EmailSerializer


class TestView(View):
    def get(self,request):
        return render(request, 'test.html')



#/test2
class TestView2(APIView):
    # def get(self,request):
    #     # print("1"+ 2)
    #     response =  Response({'message':'get请求'})
    #     #允许127.0.0.1:8080跨域调用当前接口(Django应用)
    #     # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
    #     # response['Access-Control-Allow-Origin'] = 'http://127.0.0.1:8080'
    #     return response

    def post(self,request):

        name = request.data.get('name')
        create_date = request.data.get('create_date')
        return Response({'message':'post请求',
                         'name': name,'create_date': create_date})


class UsernameCountView(APIView):

    #usernames/(?P<username>\w[5,20])/count/
    def get(self,request,username):
        count = User.objects.filter(username=username).count()

        context = {
            'username':username,
            'count':count
        }
        return Response(context)





class CreateUserView(CreateAPIView):
    """注册用户"""

    serializer_class = CreateUserSerializer


#/user/1
class UserDetailView(RetrieveAPIView):
    """查询一个用户的详情信息"""

    serializer_class = UserDetailSerializer
    # queryset = User.objects.all()

    #登录之后才能访问当前接口
    permission_classes = [IsAuthenticated]

    def get_object(self):
        return self.request.user

class EmailView(UpdateAPIView):
    """修改用户数据(邮箱)"""

    serializer_class = EmailSerializer
    #queryset = User.ojects.all()

    #登录后才能调用此接口
    permission_classes = [IsAuthenticated]

    def get_object(self):
        #表示要修改的是哪个用户对象
        return self.request.user



class VerifyEmailView(APIView):
    """激活用户邮箱"""
    #/email/verification
    def get(self,request):
        # 1.获取请求参数： token
        token = request.query_params.get('token')

        # 2.校验token合法性
        try:
            s = TimedJSONWebSignatureSerializer(settings.SECRET_KEY, 60 * 60 * 24)
            dict_data = s.loads(token)
        except:
            return Response({"message":'token无效'},status=400)

        # 3.从token中获取： user_id, email
        user_id = dict_data.get('user_id')
        email = dict_data.get('email')

        # 4.查询出要激活的用户对象
        try:
            user = User.objects.get(id=user_id,email=email)
        except User.DoesNotExist:
            return Response({'message':'用户不存在'},status=404)

        # 5.修改用户对象的激活字段为true: email_active = True
        user.email_active = True
        user.save()

        # 6.响应数据： {'message': 'ok'}
        return Response({'message':'ok'})


class AddressViewSet(mixins.CreateModelMixin,mixins.ListModelMixin,GenericViewSet):
    """用户地址管理"""
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]
    #query_set = Address.object.all()

    def get_queryset(self):
        #获取当前登录用户的地址
        #return = Address.objects.filter(user=self.request.user,is_daleted=False)
        return self.request.user.addresses.filter(is_deleted=False)


    def create(self, request, *args, **kwargs):
        count = request.user.addresses.count()
        if count >= 10:  #每个用户最多不能超过10个地址
            return Response({'message':'地址个数已达到上限'},status=400)
        return super().create(request,*args,**kwargs)

    def list(self, request, *args, **kwargs):
        """用户地址列表数据"""
        queryset=self.get_queryset()
        serializer = self.get_serializer(queryset,many=True)
        return Response({
            'user_id':request.user.id,
            'default_address_id':request.user.default_address_id,
            'limit':10,
            'addresses':serializer.data
        })

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


